# -*- coding: utf-8 -*-
import requests;
import threading;


sitedb = "list.txt";  #要检测的站点列表
errorsites = []


def readlist():
    sitefile = open(sitedb, "r");
    sites = sitefile.readlines();
    print(u"开始检测...");
    threads = []
    for site in sites:
        print(site);
        t1 = threading.Thread(target=siteStatus, args=(site,));
        t1.start();
        threads.append(t1);
    for th in threads:
        th.join();
    print(u"全部站点检测完成...");


def siteStatus(site):
    global errorsites;
    response = "";
    site = "http://" + site.strip('\n');
    try:
        response = requests.get(site);
        code = str(response.status_code);
        if code != "200":
            print(site + " : " + code);
            errorsites.append(site + " " + code);
    except requests.exceptions.HTTPError as e:
        print(site + " : " + str(e.code));
        errorsites.append(site + " " + str(e.code));
    except requests.exceptions.RequestException:
        print(site + u" 超时或访问异常");
        errorsites.append(site + u" 超时异常");
    finally:
        if response:
            response.close();


# 目前输出为网页形式，以供同事查看
def writeerror():
    print(u"将检测结果写入文件...");
    errorfile = open("index.html", "w");
    errorfile.write('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />');
    errorfile.write(u"<p>查看<a href='{0}' target='_blank'>所有网站列表</a>,目前以下站点有异常：</p>".format(sitedb));
    for ia in errorsites:
        ia2 = ia.split(' ');
        hostname = ia2[0].strip().replace("\n", "");
        errorfile.write("<a href='" + hostname + "' target='_blank'>" + ia.replace("http://www.", "") + "</a><br/>");
        errorfile.write("\n");
    errorfile.close();


# 删除已不要的站点,del.txt为删除名单 listnew.txt为新的站点表
def delsite():
    keepsites = [];
    delfile = open(basedir + "del.txt", "r");
    sitefile = open(basedir + sitedb, "r");
    delsites = delfile.readlines();
    sites = sitefile.readlines();
    for delsite in delsites:
        try:
            sites.remove(delsite);
        except ValueError:
            continue;
    newsitefile = open(basedir + "listnew.txt", "w");
    for newsite in sites:
        newsitefile.write(newsite);
    newsitefile.close();


if __name__ == '__main__':
    # siteStatus("www.tianyi-edu.com"); #单个网站测试
    readlist();
    writeerror();
    print(u"全部处理完成");
